<template>
  <div class="app-container">
    <div v-show="!detailInfo.visible && !consumeDetailInfo.visible">
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :list-type-info="listTypeInfo"
          :clear-type="clearType"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :check-box="true"
        :tab-index="true"
        :query="filterInfo.query"
        :handle="tableInfo.handle"
        :field-list="tableInfo.fieldList"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-combinationNum="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.combinationNum || '-'
          }}</span>
        </template>
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showConsumeDetail(scope.row)">{{
            scope.row.orderNo || '-'
          }}</span>
        </template>
      </table-container>
    </div>
    <detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.orderId"
      @returnBack="getList"
    />
    <consume-order-detail
      v-if="consumeDetailInfo.visible"
      :id="consumeDetailInfo.id"
      v-model:visible="consumeDetailInfo.visible"
      page-type="consume"
      @returnBack="getList"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<script setup name="chargeItemRecord">
import TableContainer from '@/components/TableContainer/index'
import { getCustomizeSetting } from '@/api/customize'
import {
  ChargeItemRecordClose,
  ChargeItemRecordConsume,
  ChargeItemRecordInsertRevoke,
  getChargeItemRecordCustomizeList,
} from '@/api/dataQuery'
import { ElMessage } from 'element-plus'
import Detail from './detail'
import ConsumeOrderDetail from '@/views/stock/consumeOrder/detail'
import { consumes } from '@/api/stock'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
// 过滤相关配置
const groupSelectInfo = reactive({
  options: [],
  selections: [],
  data: [],
})
// 查询
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    groupMap: {},
    groups: [],
    queryMap: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [],
})
const preferenceInfo = ref({
  visible: false,
})
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '耗材消耗',
        show: true,
        event: consume,
        ifRender: ifRendertransactionTypeOut,
      },
      {
        label: '耗材退回',
        show: true,
        event: insertRevoke,
        ifRender: ifRendertransactionTypeIn,
      },
      {
        label: '关闭',
        popconfirmText: '关闭后将改变数据,是否继续？',
        show: true,
        event: close,
        ifRender: ifClose,
      },
    ],
  },
})
const listTypeInfo = reactive({
  transactionTypeList: [
    { key: '耗材消耗', value: 'out' },
    { key: '耗材退回', value: 'in' },
  ],
  businessTypeList: [
    { key: '门诊', value: 'outpatient_service' },
    { key: '住院', value: 'in_hospital' },
  ],
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
//明细相关
const detailInfo = reactive({
  visible: false,
  orderId: '',
})
//明细相关
const consumeDetailInfo = reactive({
  visible: false,
  id: '',
})
const clearType = ref(true)
const groupFlag = ref(false)
const slipSelectRequest = ref(true)
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}

let obj = {
  combinationNum: {
    label: '计费组合码',
    value: 'combinationNum',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  patientCode: {
    label: '病人编码',
    value: 'patientCode',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  patientName: {
    label: '病人姓名',
    value: 'patientName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  diseasesName: {
    label: '病种',
    value: 'diseasesName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  hospitalNumber: {
    label: '住院号',
    value: 'hospitalNumber',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  doctorCode: {
    label: '主管医生编码',
    value: 'doctorCode',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  doctorName: {
    label: '主管医生姓名',
    value: 'doctorName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  executorCode: {
    label: '执行人编码',
    value: 'executorCode',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  executorName: {
    label: '执行人姓名',
    value: 'executorName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  chargeNumber: {
    label: '计费单号',
    value: 'chargeNumber',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  hisItemCode: {
    label: 'HIS计费项目编码',
    value: 'hisItemCode',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  hisItemName: {
    label: 'HIS计费项目名称',
    value: 'hisItemName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  productUnitOfMeasure: {
    label: '产品单位',
    value: 'productUnitOfMeasure',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  productLot: {
    label: '产品批号',
    value: 'productLot',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  barCode: {
    label: '条码号',
    value: 'barCode',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  orderingDeptCode: {
    label: '开单科室编码',
    value: 'orderingDeptCode',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  orderingDeptName: {
    label: '开单科室名称',
    value: 'orderingDeptName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  performedDeptCode: {
    label: '执行科室编码',
    value: 'performedDeptCode',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  performedDeptName: {
    label: '执行科室名称',
    value: 'performedDeptName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  ward: {
    label: '执行科室名称',
    value: '病区',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  orderNo: {
    label: '消耗单号',
    value: 'orderNo',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  transactionTypeValue: {
    label: '事务处理',
    value: 'transactionTypeValue',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  businessTypeValue: {
    label: '业务处理',
    value: 'businessTypeValue',
    componentType: 'input',
    show: false,
    hidden: true,
  },
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  transactionTypeId: {
    label: '事务处理',
    value: 'transactionTypeId',
    componentType: 'select',
    list: 'transactionTypeList',
    show: false,
    hidden: true,
  },
  businessType: {
    label: '业务处理',
    value: 'businessType',
    componentType: 'select',
    list: 'businessTypeList',
    show: false,
    hidden: true,
  },
  errorMsg: {
    label: '处理失败原因',
    value: 'errorMsg',
    componentType: 'solt',
    show: false,
    hidden: true,
  },
})
getCustomize()

//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.orderId = row.id
  detailInfo.visible = true
}
function showConsumeDetail(row) {
  let params = {
    orderNo: row.orderNo,
  }
  consumes(params).then((resp) => {
    if (resp && resp.success) {
      consumeDetailInfo.id = resp.data.id
      consumeDetailInfo.visible = true
    }
  })
}
function consume(row) {
  const ids = getIds(row)
  ChargeItemRecordConsume(ids).then((resp) => {
    if (resp.success) {
      tableInfo.refresh = Math.random()
    }
  })
}
function insertRevoke(row) {
  const ids = getIds(row)
  ChargeItemRecordInsertRevoke(ids).then((resp) => {
    if (resp.success) {
      tableInfo.refresh = Math.random()
    }
  })
}
function close(row) {
  const ids = getIds(row)
  ChargeItemRecordClose(ids).then((resp) => {
    if (resp.success) {
      tableInfo.refresh = Math.random()
    }
  })
}
function getIds(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((row) => row.id)
  }
  return ids
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  if (groupSelectInfo.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.data = []
    tableInfo.initCurpage = Math.random()
    tableInfo.refresh = Math.random()
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.query
  }
  if (filterInfo.query.queryDtoList && filterInfo.query.queryDtoList.length) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true
    filterInfo.query.groups = arr
    groupSelectInfo.selections = arr
    getCustomizeGroupsList()
  } else {
    ElMessage.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}
function updateGroupSelections(arr) {
  filterInfo.query.groups = arr
  groupSelectInfo.selections = arr
  if (!arr.length) {
    filterInfo.query.groups = []
    filterInfo.query.groupMap = {}
    groupSelectInfo.data = []
    groupFlag.value = false
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'HisSpdChargeItemInfoList-com.slip.spd.his.entity.vo.HisSpdChargeItemInfoVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail,
        true
      )
      tableInfo.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.options = tableFieldInfo.groupOption
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      tableInfo.api = getChargeItemRecordCustomizeList
      getList()
    }
  })
}
function ifRendertransactionTypeIn(row) {
  return row.transactionTypeId === 'in' && row.status !== 2 && row.status !== 5
}
function ifRendertransactionTypeOut(row) {
  return row.transactionTypeId == 'out' && row.status !== 2 && row.status !== 5
}
function ifClose(row) {
  return row.status !== 2 && row.status !== 5
}
</script>

<style scoped></style>
